import _regeneratorRuntime from "@babel/runtime/regenerator";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _TextArea from "choerodon-ui/pro/lib/text-area";
import _Upload from "choerodon-ui/pro/lib/upload";
import _DatePicker from "choerodon-ui/pro/lib/date-picker";
import _Lov from "choerodon-ui/pro/lib/lov";
import _Switch from "choerodon-ui/pro/lib/switch";
import _CheckBox from "choerodon-ui/pro/lib/check-box";
import _Select from "choerodon-ui/pro/lib/select";
import _NumberField from "choerodon-ui/pro/lib/number-field";
import _TextField from "choerodon-ui/pro/lib/text-field";
import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _isArray from "lodash/isArray";
var _excluded = ["isConfig"];

/* eslint-disable react/jsx-props-no-spreading */

/* eslint-disable eqeqeq */
import React from 'react';
import moment from 'moment';
import request from "../../../../utils/request";
import { getCurrentOrganizationId, getResponse, getUserOrganizationId, filterNullValueObject } from "../../../../utils/utils";
import { getEnvConfig } from "../../../../utils/iocUtils";
import { FlexLink, FlexIntlField } from "./FlexComponents";

var _getEnvConfig = getEnvConfig('config'),
    CPAAS_PLATFORM = _getEnvConfig.CPAAS_PLATFORM;
/**
 * 处理组件的特有配置
 * @param contentProps
 */


export function parseProps() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var tools = arguments.length > 1 ? arguments[1] : undefined;
  var oldConfig = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  var numberMax = props.numberMax,
      numberMin = props.numberMin,
      numberPrecision = props.numberPrecision,
      areaMaxLine = props.areaMaxLine,
      fieldType = props.fieldType,
      textMaxLength = props.textMaxLength,
      textMinLength = props.textMinLength,
      defaultValue = props.defaultValue,
      paramList = props.paramList,
      lovCode = props.lovCode,
      _props$dateFormat = props.dateFormat,
      dateFormat = _props$dateFormat === void 0 ? '' : _props$dateFormat,
      multipleFlag = props.multipleFlag;
  var commonProps = filterNullValueObject({
    maxLength: textMaxLength,
    minLength: textMinLength,
    max: numberMax,
    min: numberMin,
    defaultValue: defaultValue
  });

  if (fieldType !== undefined) {
    commonProps.type = getComponentType(fieldType);
  }

  if (fieldType === 'TEXT_AREA') {
    return _objectSpread(_objectSpread({}, commonProps), {}, {
      rows: areaMaxLine || 2
    });
  }

  if (fieldType === 'INPUT_NUMBER') {
    return _objectSpread(_objectSpread({}, commonProps), {}, {
      step: 1 / Math.pow(10, numberPrecision)
    });
  }

  if (fieldType === 'LOV') {
    return _objectSpread(_objectSpread({}, commonProps), {}, {
      multiple: multipleFlag === 1,
      lovPara: _objectSpread(_objectSpread({}, oldConfig.lovPara), getContextParams(paramList, tools)),
      lovCode: lovCode || oldConfig.lovCode
    });
  }

  if (fieldType === 'SELECT') {
    return _objectSpread(_objectSpread({}, commonProps), {}, {
      multiple: multipleFlag === 1,
      lovPara: _objectSpread(_objectSpread({}, oldConfig.lovPara), getContextParams(paramList, tools)),
      lookupCode: lovCode || oldConfig.lookupCode
    });
  }

  if (fieldType === 'DATE_PICKER') {
    return _objectSpread(_objectSpread({}, commonProps), {}, {
      format: dateFormat.replace(/hh/, 'HH'),
      type: /hh|mm|ss|HH/g.test(dateFormat) ? 'dateTime' : 'date'
    });
  }

  return commonProps;
}
export function transformCompProps() {
  var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var fieldType = props.fieldType,
      linkTitle = props.linkTitle,
      dateFormat = props.dateFormat,
      linkHref = props.linkHref,
      linkNewWindow = props.linkNewWindow,
      editable = props.editable,
      placeholder = props.placeholder,
      _props$uploadAccept = props.uploadAccept,
      uploadAccept = _props$uploadAccept === void 0 ? [] : _props$uploadAccept;
  var commonProps = {
    placeholder: placeholder
  };

  if (fieldType === 'LINK') {
    return {
      linkTitle: linkTitle,
      linkHref: linkHref,
      linkNewWindow: linkNewWindow
    };
  }

  if (fieldType === 'UPLOAD') {
    return {
      action: linkHref,
      accept: uploadAccept.join(',')
    };
  }

  if (fieldType === 'DATE_PICKER') {
    return {
      mode: /hh|mm|ss|HH/g.test(dateFormat) ? 'dateTime' : 'date'
    };
  }

  if (editable !== -1) {
    commonProps.disabled = !editable;
  }

  return commonProps;
}
/**
 * 根据类型参数生成不同的表单组件
 * @param type 组件类型
 */

export function getComponent(type, extra) {
  var Component = null;

  switch (type) {
    case 'INPUT':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_TextField, props);
      };

      break;

    case 'INPUT_NUMBER':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_NumberField, props);
      };

      break;

    case 'SELECT':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_Select, props);
      };

      break;
    // case 'RADIO_GROUP':
    //   Component = props => <FlexRadioGroup {...props} />;
    //   break;

    case 'CHECKBOX':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_CheckBox, Object.assign({}, props, {
          unCheckedValue: 0,
          checkedValue: 1
        }));
      };

      break;

    case 'SWITCH':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_Switch, Object.assign({}, props, {
          unCheckedValue: 0,
          checkedValue: 1
        }));
      };

      break;

    case 'LOV':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_Lov, props);
      };

      break;

    case 'DATE_PICKER':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_DatePicker, props);
      };

      break;

    case 'UPLOAD':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_Upload, props);
      };

      break;

    case 'TL_EDITOR':
      Component = FlexIntlField;
      break;

    case 'TEXT_AREA':
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_TextArea, props);
      };

      break;

    case 'LINK':
      Component = FlexLink;
      break;

    default:
      Component = function Component(props) {
        return /*#__PURE__*/React.createElement(_TextField, props);
      };

  }

  return function (options) {
    return Component(options, extra);
  };
}
/**
 * 根据类型参数生成不同的表单组件
 * 字段类型，可选值：boolean number string date dateTime time week month year email url intl object
 * @param type 组件类型
 */

export function getComponentType(type) {
  switch (type) {
    case 'INPUT':
      return 'string';

    case 'INPUT_NUMBER':
      return 'number';

    case 'SELECT':
      return 'string';

    case 'CHECKBOX':
    case 'SWITCH':
      return 'boolean';

    case 'LOV':
      return 'object';

    case 'DATE_PICKER':
      return 'date';

    case 'UPLOAD':
      return 'upload';

    case 'TL_EDITOR':
      return 'intl';

    case 'LINK':
      return 'url';

    default:
      return 'string';
  }
} // 查询用户个性化渲染数据

export function queryUnitCustConfig() {
  return _queryUnitCustConfig.apply(this, arguments);
} // 查询用户个性化配置数据

function _queryUnitCustConfig() {
  _queryUnitCustConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
    var params,
        _args = arguments;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) {
        switch (_context.prev = _context.next) {
          case 0:
            params = _args.length > 0 && _args[0] !== undefined ? _args[0] : {};
            _context.t0 = getResponse;
            _context.next = 4;
            return request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/ui-customize"), {
              query: params,
              method: 'GET'
            });

          case 4:
            _context.t1 = _context.sent;
            return _context.abrupt("return", (0, _context.t0)(_context.t1));

          case 6:
          case "end":
            return _context.stop();
        }
      }
    }, _callee);
  }));
  return _queryUnitCustConfig.apply(this, arguments);
}

export function queryUserCustConfig(_x) {
  return _queryUserCustConfig.apply(this, arguments);
} // 保存用户个性化配置数据

function _queryUserCustConfig() {
  _queryUserCustConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(query) {
    return _regeneratorRuntime.wrap(function _callee2$(_context2) {
      while (1) {
        switch (_context2.prev = _context2.next) {
          case 0:
            _context2.t0 = getResponse;
            _context2.next = 3;
            return request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/unit-config/user-ui"), {
              query: query
            });

          case 3:
            _context2.t1 = _context2.sent;
            return _context2.abrupt("return", (0, _context2.t0)(_context2.t1));

          case 5:
          case "end":
            return _context2.stop();
        }
      }
    }, _callee2);
  }));
  return _queryUserCustConfig.apply(this, arguments);
}

export function saveUserCustConfig(_x2) {
  return _saveUserCustConfig.apply(this, arguments);
}

function _saveUserCustConfig() {
  _saveUserCustConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(params) {
    return _regeneratorRuntime.wrap(function _callee3$(_context3) {
      while (1) {
        switch (_context3.prev = _context3.next) {
          case 0:
            _context3.t0 = getResponse;
            _context3.next = 3;
            return request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/unit-config/user-ui"), {
              method: 'POST',
              body: params
            });

          case 3:
            _context3.t1 = _context3.sent;
            return _context3.abrupt("return", (0, _context3.t0)(_context3.t1));

          case 5:
          case "end":
            return _context3.stop();
        }
      }
    }, _callee3);
  }));
  return _saveUserCustConfig.apply(this, arguments);
}

export function coverConfig() {
  var conditions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var config = arguments.length > 1 ? arguments[1] : undefined;
  var ignore = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var newConfig = {};
  conditions.forEach(function (i) {
    var _i$conExpression = i.conExpression,
        conExpression = _i$conExpression === void 0 ? '' : _i$conExpression;

    if (conExpression !== '') {
      var isErr = isErrConExpression(conExpression);

      if (!isErr && !ignore.includes(i.conType)) {
        var conNoList = conExpression.match(/\s?\d+\s?/g);
        var result = calculateExpression(i.lines || [], config);
        conNoList.forEach(function (k) {
          var newKey = k.trim();
          conExpression = conExpression.replace(newKey, result[newKey] || false);
        });
        conExpression = conExpression.replace(/AND/g, '&&').replace(/OR/g, '||'); // eslint-disable-next-line no-eval

        newConfig[i.conType] = eval(conExpression) ? 1 : 0;
      }
    }
  });
  return newConfig;
}

function isErrConExpression(exp) {
  var leftBracketNum = exp.match(/\(/g) || [].length;
  var rightBracketNum = exp.match(/\)/g) || [].length;
  var ruleConNo = /\s*\d+\s+\d+\s*/g.test(exp);
  var ruleConLogic = /\s*(AND|OR)\s*(AND|OR)\s*/g.test(exp);
  var illegalChar = /^(?!AND|OR|\(|\)|\d)/g.test(exp);
  if (leftBracketNum !== rightBracketNum || ruleConNo || ruleConLogic || illegalChar) return true;
  return false;
}

function calculateExpression(conditionList) {
  var tools = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var result = {};
  conditionList.forEach(function (i) {
    var conCode = i.conCode,
        _i$sourceFieldCode = i.sourceFieldCode,
        sourceFieldCode = _i$sourceFieldCode === void 0 ? '' : _i$sourceFieldCode,
        sourceUnitCode = i.sourceUnitCode,
        conExpression = i.conExpression,
        targetType = i.targetType,
        _i$targetFieldCode = i.targetFieldCode,
        targetFieldCode = _i$targetFieldCode === void 0 ? '' : _i$targetFieldCode,
        targetValue = i.targetValue;
    var sourceUnitType = tools.getCacheType(sourceUnitCode);
    if (!sourceUnitCode || !sourceUnitType) return result;
    var left = getFieldValueByCode(sourceUnitCode, sourceFieldCode, tools);
    var right = targetValue;

    if (targetType === 'formNow') {
      right = getFieldValueByCode(tools.code, targetFieldCode, tools);
    }

    result[conCode] = logicCompute(conExpression, left, right);
  });
  return result;
}

function logicCompute(type, left, right) {
  switch (type) {
    case '=':
      return left == right;

    case '>=':
      return left >= right;

    case '<=':
      return left <= right;

    case '!=':
      return left != right;

    case '>':
      return left > right;

    case '<':
      return left < right;

    case 'ISNULL':
      return left === undefined || left === null;

    case 'NOTNULL':
      return left !== undefined && left !== null;

    case 'BEFORE':
      return moment(left).isBefore(moment(right));

    case 'AFTER':
      return moment(left).isAfter(moment(right));

    case 'SAME':
      return moment(left).isSame(moment(right));

    case 'NOTSAME':
      return !moment(left).isSame(moment(right));

    case '~BEFORE':
      return !moment(left).isBefore(moment(right));

    case '~AFTER':
      return !moment(left).isAfter(moment(right));

    case 'LIKE':
      return new RegExp(right, 'g').test(String(left));

    case 'UNLIKE':
      return !new RegExp(right, 'g').test(String(left));

    case '~LIKE':
      return new RegExp(left, 'g').test(String(right));

    case '~UNLIKE':
      return !new RegExp(left, 'g').test(String(right));

    default:
      return false;
  }
}

export function getContextParams() {
  var paramList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];

  var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      isConfig = _ref.isConfig,
      others = _objectWithoutProperties(_ref, _excluded);

  var paramObj = {};
  var search = window.location.search;
  var urlParams = {};

  if (search) {
    search.substr(1).split('&').forEach(function (item) {
      if (item) {
        var _item$split = item.split('='),
            _item$split2 = _slicedToArray(_item$split, 2),
            key = _item$split2[0],
            value = _item$split2[1];

        urlParams[key] = value;
      }
    });
  }

  var c = getContext();
  paramList.forEach(function (item) {
    if (item.paramType === 'context') {
      switch (item.paramValue) {
        case 'organizationId':
          paramObj[item.paramKey] = c.organizationId;
          break;

        case 'tenantId':
          paramObj[item.paramKey] = c.tenantId;
          break;

        default:
      }
    } else if (item.paramType === 'url') {
      paramObj[item.paramKey] = urlParams[item.paramKey];
    } else if (item.paramType === 'fixed') {
      paramObj[item.paramKey] = item.paramValue;
    } else if (!isConfig) {
      paramObj[item.paramKey] = getFieldValueByCode(item.paramUnitCode, item.paramFieldCode, others);
    }
  });
  return paramObj;
} // 还原用户个性化配置数据

export function resetUserCustConfig(_x3) {
  return _resetUserCustConfig.apply(this, arguments);
}

function _resetUserCustConfig() {
  _resetUserCustConfig = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(params) {
    return _regeneratorRuntime.wrap(function _callee4$(_context4) {
      while (1) {
        switch (_context4.prev = _context4.next) {
          case 0:
            _context4.t0 = getResponse;
            _context4.next = 3;
            return request("".concat(CPAAS_PLATFORM, "/v1/").concat(getCurrentOrganizationId(), "/unit-config/user-ui"), {
              method: 'DELETE',
              query: params
            });

          case 3:
            _context4.t1 = _context4.sent;
            return _context4.abrupt("return", (0, _context4.t0)(_context4.t1));

          case 5:
          case "end":
            return _context4.stop();
        }
      }
    }, _callee4);
  }));
  return _resetUserCustConfig.apply(this, arguments);
}

export function getContext() {
  return {
    organizationId: getCurrentOrganizationId(),
    tenantId: getUserOrganizationId()
  };
}
export function getFieldValueObject() {
  var relatedList = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
  var tools = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  var code = arguments.length > 2 ? arguments[2] : undefined;
  var obj = {
    c: getContext()
  };
  relatedList.forEach(function (_ref2) {
    var unitCode = _ref2.unitCode,
        alias = _ref2.alias;
    var newAlias = unitCode === code ? 'self' : alias;
    obj[newAlias] = getUnitDataByCode(unitCode, tools);
  });
  return obj;
}

function getFieldValueByCode(unitCode, fieldCode) {
  var _ref3 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {},
      getArrayDataValue = _ref3.getArrayDataValue,
      getDataValue = _ref3.getDataValue,
      getCacheType = _ref3.getCacheType,
      index = _ref3.index;

  var unitType = getCacheType(unitCode);

  switch (unitType) {
    case 'form':
      return getDataValue(unitCode)[fieldCode];

    case 'table':
      return getArrayDataValue(unitCode, index)[fieldCode];

    default:
  }
}

function getUnitDataByCode(unitCode) {
  var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
      getArrayDataValue = _ref4.getArrayDataValue,
      getDataValue = _ref4.getDataValue,
      getCacheType = _ref4.getCacheType,
      index = _ref4.index;

  var unitType = getCacheType(unitCode);

  switch (unitType) {
    case 'form':
      return getDataValue(unitCode);

    case 'table':
      return getArrayDataValue(unitCode, index);

    default:
      return {};
  }
}

export function selfValidator() {
  var conValid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  var config = arguments.length > 1 ? arguments[1] : undefined;
  var _conValid$conLineList = conValid.conLineList,
      conLineList = _conValid$conLineList === void 0 ? [] : _conValid$conLineList,
      _conValid$conValidLis = conValid.conValidList,
      conValidList = _conValid$conValidLis === void 0 ? [] : _conValid$conValidLis;
  conLineList = _isArray(conLineList) ? conLineList : [];
  conValidList = _isArray(conValidList) ? conValidList : [];
  var result = calculateExpression(conLineList, config);
  var validation = [];
  conValidList.forEach(function (i) {
    var newExpression = i.conExpression;
    var isErr = isErrConExpression(newExpression);

    if (!isErr) {
      var conNoReg = /(\d+)/g;
      newExpression = newExpression.replace(conNoReg, function (_, m) {
        return result[m] || false;
      });
      newExpression = newExpression.replace(/AND/g, '&&').replace(/OR/g, '||'); // eslint-disable-next-line no-new-func

      validation.push({
        // eslint-disable-next-line no-new-func
        isCorrect: new Function("return ".concat(newExpression, ";"))(),
        message: i.errorMessage
      });
    }
  });

  if (validation.length > 0) {
    return {
      customize: true,
      validator: function validator() {
        for (var k = 0; k < validation.length; k += 1) {
          if (!validation[k].isCorrect) {
            // eslint-disable-next-line no-useless-return
            return validation[k].message;
          }
        }

        return true;
      }
    };
  }

  return {};
}